require 'open-uri'
require 'erb'
require 'hpricot_fix'

require 'zlib'
require 'stringio'



class ProxyingController < ApplicationController
    helper :proxying
    include ProxyingHelper
    include ProxyingUrlHandlerHelper
    skip_before_filter :verify_authenticity_token
    after_filter OutputCompressionFilter
    before_filter :initialize_agent
    after_filter :dump_agent

    define_url_handler /bbs\.uubird/, :remove_location_replace
    define_url_handler /btchina/, :remove_location_replace
    define_url_handler(/btchina/) {|url, doc| puts "nnn:#{url}"}
    #define_url_handler /bbs\.uubird/, :append_base
    #define_url_handler /bbs/, :remove_meta_refresh
    class  UrlHandle
        def self.url_handle(url, doc)
            puts "url handler using class:#{url}"
        end
    end
    define_url_handler /btchina/, UrlHandle


    alias original_rescue_action rescue_action

    def rescue_action(e)
        puts e.backtrace.join("\n")
        original_rescue_action(e)
    end

    def index
        
        @url = params[:id] || params[:q]

        if request.post?
            do_post()
        else
            do_get()
        end

    end

    def store
        url = params[:id]
        puts "storing #{url}"
    end

    private

    def do_post

        puts "posting #{@url}"
        @url = "http://"+ @url unless URI(@url).scheme

        fix_params #remove controller, action ect params

        @page = @agent.post(@url, params)

        @doc = @page.search("")


        rewrite_link_for_doc(@doc)

        url_handle(@url, @doc, self)

        render :text=>fix_result,
                :content_type => fix_contentType

    end

    def do_get
        puts "fetching #{@url}" #if request.get?
        @url = "http://"+ @url unless URI(@url).scheme


        @page = @agent.get(@url)
        @doc = @page.search("")


        rewrite_link_for_doc(@doc)
        url_handle(@url, @doc, self)


        render :text=>fix_result,
                :content_type => fix_contentType
    end

    def url_handle(url, doc, object)
        self.class.handle(url, doc, object)
    end


end
